package net.flydy.ywxcx.wxcloudrun.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Service;

/**
 * @author flydy
 */
@Service
public class MyCacheService {
    @Autowired
    @Qualifier("selfCacheManager")
    CacheManager selfCacheManager;

    public void put(String key, Object data, int ttl, boolean nullAble) {
        put(LocalCacheConfig.CACHENAME_DEFAULT, key, data, ttl, nullAble);
    }

    public void put(String cacheName, String key, Object data, int ttl, boolean nullAble) {
        if (!nullAble && data == null) {
            return;
        }
        CacheEntity ce = new CacheEntity(data, ttl);
        selfCacheManager.getCache(cacheName).put(key, ce);
    }

    public <T> T get(String key) {
        return get(LocalCacheConfig.CACHENAME_DEFAULT, key);
    }

    public <T> T get(String cacheName, String key) {
        CacheEntity<T> ce = selfCacheManager.getCache(cacheName).get(key, CacheEntity.class);
        if (ce != null) {
            return ce.getData();
        }
        return null;
    }

    public <T> CacheEntity<T> getWraper(String cacheName, String key) {
        CacheEntity<T> ce = selfCacheManager.getCache(cacheName).get(key, CacheEntity.class);
        return ce;
    }

    public <T> CacheEntity<T> getWraper(String key) {
        return getWraper(LocalCacheConfig.CACHENAME_DEFAULT, key);
    }

}
